<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <!--      <el-col :span="4" :xs="24">-->
      <!--        <div class="head-container">-->
      <!--          <el-input-->
      <!--            v-model="itemBomTypeName"-->
      <!--            placeholder="请输入分类名称"-->
      <!--            clearable-->
      <!--            size="small"-->
      <!--            prefix-icon="el-icon-search"-->
      <!--            style="margin-bottom: 20px"-->
      <!--          />-->
      <!--        </div>-->
      <!--        <div class="head-container">-->
      <!--          <el-tree-->
      <!--            :data="itemBomTypeOptions"-->
      <!--            :props="defaultProps"-->
      <!--            :expand-on-click-node="false"-->
      <!--            :filter-node-method="filterNode"-->
      <!--            :default-expanded-keys="treeData"-->
      <!--            ref="tree"-->
      <!--            node-key="id"-->
      <!--            highlight-current-->
      <!--            @node-click="handleNodeClick"-->
      <!--          />-->
      <!--        </div>-->
      <!--      </el-col>-->
      <!--产品数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="BOM版本" prop="bomItemCode">
            <el-input v-model="queryParams.bomItemCode" placeholder="请输入BOM版本" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="父项物料编码" prop="itemCode">
            <el-input v-model="queryParams.itemCode" placeholder="请输入父项物料编码" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="primary"-->
          <!--              plain-->
          <!--              icon="el-icon-plus"-->
          <!--              size="mini"-->
          <!--              @click="handleAdd"-->
          <!--              v-hasPermi="['system:bom:add']"-->
          <!--            >新增-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="success"-->
          <!--              plain-->
          <!--              icon="el-icon-edit"-->
          <!--              size="mini"-->
          <!--              :disabled="single"-->
          <!--              @click="handleUpdate"-->
          <!--              v-hasPermi="['system:bom:edit']"-->
          <!--            >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="danger"-->
          <!--              plain-->
          <!--              icon="el-icon-delete"-->
          <!--              size="mini"-->
          <!--              :disabled="multiple"-->
          <!--              @click="handleDelete"-->
          <!--              v-hasPermi="['system:bom:remove']"-->
          <!--            >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!-- <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['mes:pro:proBom:import']"
               v-hasPermi="['mes:pro:proBom:import']"
              >导入</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['mes:proBom:export']">导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="synchronous" v-hasPermi="['mes:proBom:syncdata']">同步数据</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" align="center" width="70" />
          <el-table-column label="BOM版本" width="160" prop="bomItemCode">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleView(scope.row)">
                {{ scope.row.bomItemCode }}
              </el-button>
            </template>
          </el-table-column>
          <!--          <el-table-column label="BOM简称" width="210" prop="bomItemName"/>-->
          <!--          <el-table-column label="BOM分类" width="210" prop="jdyBomCateguory"/>-->
          <el-table-column label="BOM分组" width="250" align="center" prop="groupName" />
          <el-table-column label="父项物料编码" width="160" align="center" prop="itemCode" />
          <!--          <el-table-column label="金蝶云物料清单分类ID" align="center" prop="jdyBomId" v-if="false"/>-->
          <el-table-column label="物料名称" align="center" width="180" prop="itemName" />
          <el-table-column label="规格型号" align="center" width="260" prop="specification" />
          <el-table-column label="是否新版本" align="center" prop="jdyIsDefault">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.bom_yes_no" :value="scope.row.jdyIsDefault" />
            </template>
          </el-table-column>
          <el-table-column label="数据状态" align="center" prop="enableFlag">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.md_product_bom" :value="scope.row.enableFlag" />
            </template>
          </el-table-column>
          <!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
          <!--            <protemplate slot-scope="scope">-->
          <!--              <el-button-->
          <!--                size="mini"-->
          <!--                type="text"-->
          <!--                icon="el-icon-edit"-->
          <!--                @click="handleUpdate(scope.row)"-->
          <!--                v-hasPermi="['system:bom:edit']"-->
          <!--              >修改-->
          <!--              </el-button>-->
          <!--              <el-button-->
          <!--                size="mini"-->
          <!--                type="text"-->
          <!--                icon="el-icon-delete"-->
          <!--                @click="handleDelete(scope.row)"-->
          <!--                v-hasPermi="['system:bom:remove']"-->
          <!--              >删除-->
          <!--              </el-button>-->
          <!--            </protemplate>-->
          <!--          </el-table-column>-->
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="[10, 30, 50, 100, 150]" @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改产品BOM关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <!-- 2025-1-3 djj 新增导出 -->
      <button @click="exportExcelBtn" :disabled="downloadDisabled != 3">导出Excel</button>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="BOM版本" prop="bomItemCode">
              <el-input v-model="form.bomItemCode" readonly="readonly" maxlength="64" v-if="optType == 'view'" />
              <el-input v-model="form.bomItemCode" placeholder="请输入BOM版本" maxlength="64" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM简称" prop="bomItemName">
              <el-input v-model="form.bomItemName" maxlength="255" readonly="readonly" v-if="optType == 'view'" />
              <el-input v-model="form.bomItemName" placeholder="请输入BOM简称" maxlength="255" v-else />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="BOM分组" prop="groupName">
              <el-input v-model="form.groupName" readonly="readonly" maxlength="64" v-if="optType == 'view'" />
              <el-input v-model="form.groupName" placeholder="请输入BOM分组" maxlength="64" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" readonly="readonly" maxlength="64" v-if="optType == 'view'" />
              <el-input v-model="form.specification" placeholder="请输入规格型号" maxlength="64" v-else />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="父项物料编码" prop="itemId">
              <el-input v-model="form.itemCode" type="textarea" maxlength="500" readonly="readonly" v-if="optType == 'view'" />
              <el-input v-model="form.itemCode" type="textarea" placeholder="请输入父项物料编码" maxlength="500" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" type="textarea" maxlength="500" readonly="readonly" v-if="optType == 'view'" />
              <el-input v-model="form.itemName" type="textarea" placeholder="请输入物料名称" maxlength="500" v-else />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据状态">
              <el-radio-group v-model="form.enableFlag" disabled v-if="optType == 'view'">
                <el-radio v-for="dict in dict.type.md_product_bom" :key="dict.value" :label="dict.value">{{ dict.label
                  }}
                </el-radio>
              </el-radio-group>
              <el-radio-group v-model="form.enableFlag" v-else>
                <el-radio v-for="dict in dict.type.md_product_bom" :key="dict.value" :label="dict.value">{{ dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" readonly v-if="optType == 'view'"></el-input>
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" v-else></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card" v-if="form.itemId != null">
        <el-tab-pane label="BOM组成">
          <bomIndex :optType="optType" :itemId="form.itemId" :bomItemCode="form.bomItemCode" @getBomGroupList="getBomGroupList"></bomIndex>
        </el-tab-pane>
        <!--        <el-tab-pane label="供应商"></el-tab-pane>-->
        <!--        <el-tab-pane label="替代品"></el-tab-pane>-->
        <!--        <el-tab-pane label="SIP"></el-tab-pane>-->
        <!--        <el-tab-pane label="SOP">-->
        <!--          <SOPTab :itemId="form.itemId" :optType="optType"></SOPTab>-->
        <!--        </el-tab-pane>-->
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- BOM导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的BOM数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBom,
  getBom,
  delBom,
  addBom,
  updateBom,
  treeselect,
  synchronousData,
} from "@/api/mes/md/bom";
import Treeselect from "@riophae/vue-treeselect";
import bomIndex from "./components/bomIndex.vue";
import { getProcess } from "@/api/mes/pro/process";
import { getToken } from "@/utils/auth";
import moment from "moment";
/* import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver'; */
import { exportExcel } from "@/utils/request";
export default {
  name: "ProBom",
  dicts: ["md_product_bom", "bom_yes_no"],
  components: { Treeselect, bomIndex },
  data() {
    return {
      downloadDisabled: 0,
      bomGroupList: null,
      // BOM导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的BOM数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/md/bom/importData",
      },
      //弹框的操作类型 view add edit
      optType: undefined,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 类型树选项
      itemBomTypeOptions: undefined,
      // 类型名称
      itemBomTypeName: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品BOM关系表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        bomGroup: null,
        pageNum: 1,
        pageSize: 10,
        itemCode: null,
        itemId: null,
        bomItemId: null,
        bomItemCode: null,
        bomItemName: null,
        bomItemSpec: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        quantity: null,
        enableFlag: null,
        isAll: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemId: [
          { required: true, message: "物料产品ID不能为空", trigger: "blur" },
        ],
        bomItemId: [
          { required: true, message: "BOM物料ID不能为空", trigger: "blur" },
        ],
        bomItemCode: [
          { required: true, message: "BOM物料编码不能为空", trigger: "blur" },
        ],
        unitOfMeasure: [
          { required: true, message: "BOM物料单位不能为空", trigger: "blur" },
        ],
        itemOrProduct: [
          { required: true, message: "产品物料标识不能为空", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "物料使用比例不能为空", trigger: "blur" },
        ],
        enableFlag: [
          { required: true, message: "是否启用不能为空", trigger: "blur" },
        ],
        jdyBomId: [
          {
            required: true,
            message: "金蝶云物料清单分类ID不能为空",
            trigger: "blur",
          },
        ],
        jdyEntityId: [
          {
            required: true,
            message: "金蝶云子项明细ID不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选分类树
    itemBomTypeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    getBomGroupList(bomGroupList) {
      this.bomGroupList = bomGroupList;
      this.downloadDisabled = this.downloadDisabled + 2;
    },
    /** 查询产品BOM关系列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then((response) => {
        console.info("response.data group", response.rows);
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        console.info("response.data===>", response.data[0].children);
        this.treeData.push(response.data[0].id);
        response.data[0].children.forEach((zz) => {
          this.treeData.push(zz.id);
        });
        this.itemBomTypeOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.info("data===>", data.id);
      this.queryParams.bomGroup = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.downloadDisabled = 0;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bomId: null,
        itemId: null,
        bomItemId: null,
        bomItemCode: null,
        bomItemName: null,
        bomItemSpec: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        quantity: null,
        enableFlag: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        jdyBomId: null,
        jdyUpdateTime: null,
        jdyDosageType: null,
        jdyNumerator: null,
        jdyDenominator: null,
        jdyFixScrapQty: null,
        jdyScrapRate: null,
        replacePolicy: null,
        replaceType: null,
        replacePriority: null,
        isKeyItem: null,
        jdyEntityId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.itemId);
      this.queryParams.mdProductBomIdList = selection.map(
        (item) => item.itemId
      );
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品BOM关系";
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const jdyBomId = row.jdyBomId || this.ids;
      getBom(jdyBomId).then((response) => {
        this.form = response.data;
        this.downloadDisabled += 1;
        this.open = true;
        this.title = "查看产品BOM信息";
        this.optType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const jdyBomId = row.jdyBomId || this.ids;
      console.info("jdyBomId", jdyBomId);
      getBom(jdyBomId).then((response) => {
        console.info(response.data, "12121212121");
        this.form = response.data;
        this.open = true;
        this.title = "修改产品BOM关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.bomId != null) {
            updateBom(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBom(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bomIds = row.bomId || this.ids;
      this.$modal
        .confirm('是否确认删除产品BOM关系编号为"' + bomIds + '"的数据项？')
        .then(function () {
          return delBom(bomIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/md/bom/export",
        {
          ...this.queryParams,
        },
        `产品BOM_${moment(new Date()).format('yyyyMMDDHHmmss')}.xlsx`
      );
    },
    /** 同步 */
    synchronous() {
      this.queryParams.isAll = 0;
      synchronousData(this.queryParams).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: "数据同步成功",
            type: "success",
          });
        } else {
          throw new Error("数据同步失败");
        }
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "BOM数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "mes/md/bom/importTemplate",
        {},
        `template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /* 导出产品BOM详情 */
    exportExcelBtn() {
      let dataStructure = {
        sep: "BOM组成",
      }
      let cloneForm = JSON.parse(JSON.stringify(this.form));
      cloneForm.enableFlag = this.dict.type.md_product_bom.filter(item => item.value == cloneForm.enableFlag)[0].label;
      let formObj = {
        labelFieldMap: {
          "bomItemCode": "BOM版本",
          "bomItemName": "BOM简称",
          "groupName": "BOM分组",
          "specification": "规格型号",
          "itemId": "父项物料编码",
          "itemName": "物料名称",
          "enableFlag": "数据状态",
          "remark": {
            display: "block",
            label: "备注",
          }
        },
        valueFieldMap: cloneForm
      }
      dataStructure.form = formObj;
      let listObj = {
        labelFieldMap: {
          "itemCode": "子项物料编号",
          "sonname": "子项物料名称",
          "specification": "规格型号",
          "quantity": "使用比例",
          "measureName": "子项单位",
          "itemOrProduct": "产品物料标识",
          "jdyNumerator": "用量：分子",
          "jdyDenominator": "用量：分母",
          "jdyFixScrapQty": "固定损耗"
        },
        data: this.bomGroupList
      }
      dataStructure.list = listObj;
      exportExcel(dataStructure, "产品BOM详情");
    },
  },
};
</script>
